<template>
    <div
        style="padding-top: 40px"
        v-loading="loading"
        element-loading-text="正在搜索中，请稍等"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
    >
        <el-form :inline="false" :model="dataForm" size="mini" class="demo-form-inline" label-width="120px" ref="ruleForm">
            <!-- #1.基本信息 -->

            <el-form-item label="基础信息：" style="font-weight: bold"> </el-form-item>

            <el-form-item label="账号" prop="userId">
                <el-input v-model="dataForm.userId" placeholder="请输入账号"   :disabled='dialogType==2'  clearable></el-input>
            </el-form-item>

            <el-form-item label="类型" prop="userType">
                <el-select v-model="dataForm.userType" placeholder="请选择">
                    <el-option v-for="(item, index) in approves" :key="index" :label="item.lable" :value="item.userType"> </el-option>
                </el-select>
            </el-form-item>


            <el-form-item v-if="dialogType == 1" label="密码" prop="userPwd">
                <el-input v-model="dataForm.userPwd" placeholder="请输入密码，字母+数字" show-password></el-input>
            </el-form-item>

            <el-form-item label="名称" prop="userName">
                <el-input v-model="dataForm.userName" placeholder="请输入名称"  clearable></el-input>
            </el-form-item>

            <el-form-item label="联系人" prop="linkman">
                <el-input v-model="dataForm.linkman" placeholder="请输入联系人"  clearable></el-input>
            </el-form-item>

            <el-form-item v-if="dialogType == 1" label="联系电话" prop="concactPhone">
                <el-input
                    v-model="dataForm.concactPhone"
                    placeholder="请输入联系电话，数字"
                    clearable
                    oninput="value=value.replace(/[^\d]/g,'')"
                    maxlength="11"
                ></el-input>
            </el-form-item>

            <el-form-item v-else label="联系电话" prop="phone">
                <el-input
                    v-model="dataForm.phone"
                    placeholder="请输入联系电话，数字"
                    clearable
                    oninput="value=value.replace(/[^\d]/g,'')"
                    maxlength="11"
                ></el-input>
            </el-form-item>

            <el-form-item label="签约手机" prop="signPhone">
                <el-input
                    v-model="dataForm.signPhone"
                    placeholder="请输入签约手机，数字"
                    clearable
                    oninput="value=value.replace(/[^\d]/g,'')"
                    maxlength="11"
                ></el-input>
            </el-form-item>

            <el-form-item label="地址" prop="addr">
                <el-input v-model="dataForm.addr" :placeholder="addrPlaceholder" :disabled="addrDisabled"></el-input>
            </el-form-item>

            <!-- 百度地图  -->
            <baidu-map
                :center="center"
                :zoom="zoom"
                @ready="handler"
                style="height: 408px; margin: 15px 15px 10px 80px"
                @click="getClickInfo"
                :scroll-wheel-zoom="true"
            >
                <!-- 定位 -->
                <bm-geolocation anchor="BMAP_ANCHOR_BOTTOM_RIGHT" :showAddressBar="true" :autoLocation="true"></bm-geolocation>

                <!-- 自定义搜索框 -->
                <bm-control style="margin: 15px" v-if="isVisible">
                    <el-input v-model="inputSearchAddr" placeholder="搜索地址" style="height: 100px; width: 400px"  clearable></el-input>
                    <el-button type="primary" @click="searchClick()" style="margin-left: 10px">搜索</el-button>
                    <el-button type="primary" @click="enterAddrClick()" style="margin-left: 10px">手动输入地址</el-button>
                </bm-control>

                <!-- bm-local-search是自带的搜索功能,双向绑定 keyword 可以进行搜索 -->
                <bm-local-search
                    :keyword="searchAddr"
                    :auto-viewport="false"
                    :selectFirstResult="true"
                    :location="location"
                    :panel="true"
                    v-on:searchcomplete="searchComplete"
                    style="display: none"
                >
                </bm-local-search>
            </baidu-map>

            <el-form-item label="详细介绍" prop="detailDescribe">
                <el-input type="textarea" :rows="3" v-model="dataForm['detailDescribe']" placeholder="请输入详细介绍" clearable />
            </el-form-item>

            <el-row>
                <el-form-item label="图片">
                    <moreUpload
                        :initfileList="surfacePlotListUrl"
                        :isMultiple="true"
                        :upFileNum="5"
                        @moreUpFileHandleRemove="iconMoreUpFileHandleRemove"
                        @update="updateIconUrl"
                    ></moreUpload>
                </el-form-item>
            </el-row>

            <el-row>
                <el-form-item label="视频">
                    <moreUpVideo
                        :isShowFileList="true"
                        :isMultiple="true"
                        :isClickClearList="false"
                        :upFileNum="5"
                        :initfileList="videoUrlListUrl"
                        @moreUpFileSuccessHandle="moreUpVideoSuccessHandle"
                        @moreUpFileHandleRemove="moreUpVideohandleRemove"
                        @moreUpFileErrorHandle="moreUpVideoFileErrorHandle"
                        @moreUpFileHandleExceed="moreUpVideoFileHandleExceed"
                    >
                    </moreUpVideo>
                </el-form-item>
            </el-row>

            <!-- #2.工商信息 -->
            <el-form-item label="工商信息：" style="font-weight: bold"> </el-form-item>

            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="企业名称" prop="fullName">
                        <el-input v-model="dataForm.fullName" placeholder="请输入企业名称"  clearable> </el-input>
                    </el-form-item>
                </el-col>

                <el-col :span="12">
                    <el-form-item label="营业执照号码" prop="certificateId">
                        <el-input v-model="dataForm.certificateId" placeholder="请输入营业执照号码"  clearable> </el-input>
                    </el-form-item>
                </el-col>

                <el-col :span="12">
                    <el-form-item label="注册地址" prop="certificateUrl">
                        <el-input v-model="dataForm.certificateUrl" placeholder="请输入注册地址"  clearable> </el-input>
                    </el-form-item>
                </el-col>
            </el-row>

            <!-- #3.保存和提交按钮 -->
            <el-form-item>
                <el-button @click="$router.go(-1)">取消</el-button>
                <el-button type="primary" style="padding: 10px 40px" @click="addAndEditSubmit('ruleForm')">保存</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import API from '@/api';
import upload from '../../components/upLoad';
import cloneDeep from 'lodash/cloneDeep';
import { BmLocalSearch } from 'vue-baidu-map';
import moreUpload from '../../components/upLoad/moreUpload';
import moreUpVideo from '../../components/upLoad/moreUpVideo';

export default {
    components: {
        upload,
        BmLocalSearch,
        moreUpload,
        moreUpVideo
    },

    data() {
        return {
            dialogType: 1,

            //表单
            dataForm: {
                //基本信息
                userId: '',
                userPwd: '',
                userName: '',
                linkman: '',
                concactPhone: '',
                phone: '',
                signPhone: '',

                addr: '',
                latitude: 0,
                longitude: 0,
                detailDescribe: '',
                surfacePlot: '', //图片
                videoUrl: '', //视频

                //工商信息
                fullName: '',
                certificateId: '',
                certificateUrl: ''
            },

            center: { lng: 0, lat: 0 },
            zoom: 3,
            inputSearchAddr: '',
            location: '',
            searchAddr: '',
            loading: false,
            addrDisabled: true,
            addrPlaceholder: '请在地图上选择地址',
            isVisible: false, //是否可见

            //图片
            surfacePlotList: [],
            surfacePlotListUrl: [],

            //视频
            videoUrlList: [],
            videoUrlListUrl: [],
            approves: [{userType: 'PERSON', lable: '个人'},{userType: 'CORP',lable: '企业'}],
        };
    },

    beforeMount() {
        var type = this.$route.query.type;
        this.dialogType = type;
        this.$route.meta.title = '商户信息管理';
    },
    mounted() {
        if (this.dialogType == 2) {
            var id = this.$route.query.itemData.userId;
            this.getDeail(id); // 获取详情
        }
    },

    methods: {
        //- 清空新增中的数据
        clearForm() {
            this.dataForm = {
                //基本信息
                userId: '',
                userPwd: '',
                userName: '',
                linkman: '',
                concactPhone: '',
                signPhone: '',
                addr: '',
                latitude: 0,
                longitude: 0,
                surfacePlot: '', //图片
                videoUrl: '', //视频
                detailDescribe: 0,

                //工商信息
                fullName: '',
                certificateId: '',
                certificateUrl: ''
            };

            //图片
            this.surfacePlotList = [];
            this.surfacePlotListUrl = [];

            //视频
            this.videoUrlList = [];
            this.videoUrlListUrl = [];
        },

        /**
         * 图片 上传
         */

        // 图片 上传文件  成功回调
        updateIconUrl([url, sigleImgId, response, file, fileList]) {
            this.diosposeImageOp([file, fileList]);
        },
        // 删除文件回调
        iconMoreUpFileHandleRemove([file, fileList]) {
            this.diosposeImageOp([file, fileList]);
        },
        diosposeImageOp([file, fileList]) {
            this.surfacePlotList = [];

            for (let index = 0; index < fileList.length; index++) {
                const element = fileList[index];
                console.log('上传的图片：', element);

                if (element.response != null) {
                    //不等于空为刚上传的文件
                    this.surfacePlotList.push(element.response.result[0] + ':' + element.name);
                } else {
                    //为空为之前上传的文件
                    this.surfacePlotList.push(element.urlId + ':' + element.name);
                }
            }
        },

        /**
         * 视频 上传
         */

        //视频 上传文件  成功回调
        moreUpVideoSuccessHandle([url, sigleImgId, response, file, fileList]) {
            this.diosposeFileOp([file, fileList]);
        },
        // 删除文件回调
        moreUpVideohandleRemove([file, fileList]) {
            this.diosposeFileOp([file, fileList]);
        },
        diosposeFileOp([file, fileList]) {
            this.videoUrlList = [];

            for (let index = 0; index < fileList.length; index++) {
                const element = fileList[index];
                console.log('视频多文件上传回调：', element);

                if (element.response != null) {
                    //不等于空为刚上传的文件
                    this.videoUrlList.push(element.response.result[0] + ':' + element.name);
                } else {
                    //为空为之前上传的文件
                    this.videoUrlList.push(element.urlId + ':' + element.name);
                }
            }
        },

        //视频 上传文件 失败回调
        moreUpVideoFileErrorHandle(val) {
            this.$message.error(`文件上传失败`);
        },

        //视频 多文件上传，超出限制回调
        moreUpVideoFileHandleExceed([files, fileList]) {
            this.$message.warning(
                `当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`
            );
        },

        disposePublicStrSplit(fileStr, splicList, splicUrlList, splicFlag, urlConnection) {
            //字符串，拆分id数组，拆分Url数组，拆分标识，url前缀

            if (fileStr != null && fileStr !== '') {
                //== 1.拆分字符串 ’a:b,b:a‘ 为数组
                splicList = fileStr.split(',');

                for (let index = 0; index < splicList.length; index++) {
                    //== 2.数组中的 ’a:b‘ 在拆分 为数组
                    const element = splicList[index];
                    var elmentList = element.split(':');

                    //== 3.向 上传 绑定的数据集，添加[name，url，id] 数据
                    if (elmentList.length > 0) {
                        if (splicFlag === 'url') {
                            //文件名，文件地址（url)，文件id
                            splicUrlList.push({ name: elmentList[1], url: urlConnection + elmentList[0], urlId: elmentList[0] });
                        } else {
                            //文件名，文件地址(可id或url)，文件id
                            splicUrlList.push({ name: elmentList[1], url: elmentList[0], urlId: elmentList[0] });
                        }
                    } else {
                        //== 3.x  做预防,有可能字符串为’a,b‘ 没有分号

                        if (splicFlag === 'url') {
                            splicUrlList.push({ name: '文件' + index, url: urlConnection + element, urlId: element });
                        } else {
                            //文件名，文件地址(可id或url)，文件id
                            splicUrlList.push({ name: '文件' + index, url: element, urlId: element });
                        }
                    }
                }
            }
        },
        //百度地图
        handler({ BMap, map }) {
            this.map = map;

            //自动定位设置中心点
            let _this = this;
            var geolocation = new BMap.Geolocation();
            geolocation.getCurrentPosition(
                function (r) {
                    console.log(r);
                    if (this.getStatus() == BMAP_STATUS_SUCCESS) {
                        _this.center = { lng: r.longitude, lat: r.latitude };
                        _this.zoom = 17;

                        var translateCallback = function (data) {
                            //坐标转换完之后的回调函数
                            console.log(data);
                            console.log(data.status);
                            if (data.status === 0) {
                                if (_this.dialogType == 2) {
                                    //编辑
                                    var point = new BMap.Point(_this.dataForm.longitude, _this.dataForm.latitude);
                                    var marker = new BMap.Marker(point);
                                    map.addOverlay(marker);
                                    var label = new BMap.Label('位置', { offset: new BMap.Size(20, -10) });
                                    marker.setLabel(label); //添加百度label
                                    map.setCenter(point);
                                    _this.zoom = 17;
                                } else {
                                    //其他

                                    var marker = new BMap.Marker(data.points[0]);
                                    map.addOverlay(marker);
                                    var label = new BMap.Label('当前我的定位', { offset: new BMap.Size(20, -10) });
                                    marker.setLabel(label); //添加百度label
                                    map.setCenter(data.points[0]);
                                }

                                _this.isVisible = true;
                            }
                        };

                        setTimeout(() => {
                            var convertor = new BMap.Convertor();
                            var pointArr = [];

                            var ggPoint = new BMap.Point(_this.center.lng, _this.center.lat);
                            pointArr.push(ggPoint);
                            convertor.translate(pointArr, 1, 5, translateCallback);
                        }, 1000);
                    } else {
                        console.log('map location failed', this.getStatus());
                    }
                },
                { enableHighAccuracy: true }
            );

            // 添加鼠标滚动缩放
            map.enableScrollWheelZoom();

            // 添加缩放平移控件
            map.addControl(new BMap.NavigationControl({ isOpen: false, anchor: BMAP_ANCHOR_TOP_RIGHT }));

            //添加比例尺控件
            map.addControl(new BMap.ScaleControl());
        },

        getClickInfo(e) {
            console.log('点击的地图位置信息：', e);

            //移动地图中心位置
            this.center.lng = e.point.lng;
            this.center.lat = e.point.lat;
            this.zoom = e.target.getZoom();

            //清空标记
            this.map.clearOverlays();

            // 利用坐标获取地址的详细信息
            let geoCoder = new BMap.Geocoder();
            geoCoder.getLocation(e.point, (res) => {
                console.log('获取的搜索地址：', res);
                let addr = res.address;

                if (res.surroundingPois.length > 0) {
                    addr = addr + res.surroundingPois[0].title;

                    this.dataForm.addr = addr;
                    this.dataForm.longitude = res.surroundingPois[0].point.lng;
                    this.dataForm.latitude = res.surroundingPois[0].point.lat;

                    //重绘标记
                    var mk = new BMap.Marker(res.surroundingPois[0].point);
                    this.map.addOverlay(mk);
                    this.searchAddr = '';
                } else {
                    this.dataForm.addr = addr;
                    this.dataForm.longitude = e.point.lng;
                    this.dataForm.latitude = e.point.lat;

                    //重绘标记
                    var mk = new BMap.Marker(e.point);
                    this.map.addOverlay(mk);
                    this.searchAddr = '';
                }
            });
        },

        //地图 搜索点击
        searchClick() {
            this.addrDisabled = true;
            this.addrPlaceholder = '请在地图上选择地址';
            if (this.inputSearchAddr === '') {
                this.$message({
                    message: `请输入搜索地址`,
                    type: 'success'
                });

                return;
            }

            this.loading = true;
            this.searchAddr = this.inputSearchAddr;

            //最多60秒，不等完成 要消失
            setTimeout(() => {
                this.loading = false;
            }, 600000);
        },

        searchComplete(val) {
            this.loading = false;
            console.log('搜索完成监听：', val);
            if (val != null && val.Hr != null && val.Hr.length > 0) {
                // 利用坐标获取地址的详细信息
                let geoCoder = new BMap.Geocoder();
                geoCoder.getLocation(val.Hr[0].point, (res) => {
                    console.log('获取的搜索地址：', res);
                    let addr = res.address;

                    if (res.surroundingPois.length > 0) {
                        addr = addr + res.surroundingPois[0].title;

                        this.dataForm.addr = addr;
                        this.dataForm.longitude = res.surroundingPois[0].point.lng;
                        this.dataForm.latitude = res.surroundingPois[0].point.lat;
                    } else {
                        this.dataForm.addr = addr;
                        this.dataForm.longitude = e.point.lng;
                        this.dataForm.latitude = e.point.lat;
                    }
                });
            }
        },

        //手动输入地址
        enterAddrClick() {
            this.addrDisabled = false;
            this.addrPlaceholder = '手动输入的地址，地图上会正常显示';
            this.$message({
                message: `手动输入的地址，地图上会无法正常显示`,
                type: 'success'
            });
        },

        // 获取详情
        getDeail(id) {
            var _that = this;
            API.baseInfoManger.baseInfoDetails({ userId: id }).then((res) => {
                console.log(res);
                _that.dataForm = res.result;

                //处理图片
                var imgUrlQz = window.baseUrl + '/sys/file/showpic?id=';

                //======= 字符串，拆分id数组，拆分Url数组，拆分标识，url前缀
                this.disposePublicStrSplit(_that.dataForm.surfacePlot, _that.surfacePlotList, _that.surfacePlotListUrl, 'url', imgUrlQz);

                //处理视频

                //======= 字符串，拆分id数组，拆分Url数组，拆分标识，url前缀
                this.disposePublicStrSplit(_that.dataForm.videoUrl, _that.videoUrlList, _that.videoUrlListUrl, 'id', '');
            });
        },

        //- 新增或编辑
        addAndEditSubmit(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    let params = cloneDeep(this.dataForm);

                    //处理联系人
                    if (this.dialogType == 2) {
                        params.concactPhone = params.phone;
                    }

                    //图片和视频校验
                    if (this.dialogType == 1) {
                        if (this.surfacePlotList.length == 0 && this.videoUrlList.length == 0) {
                            this.$message.error('图片和视频，需要任意选择一个上传');
                            return;
                        }
                    } else {

                         //处理数据赋值
                        if (this.surfacePlotListUrl.length == 0 && this.surfacePlotList.length > 0) {
                            this.surfacePlotListUrl = this.surfacePlotList;
                        }
                        if(this.videoUrlListUrl.length == 0 && this.videoUrlList.length > 0){
                            this.videoUrlListUrl=this.videoUrlList;
                        }


                        if (this.surfacePlotListUrl.length == 0 && this.videoUrlListUrl.length == 0) {
                            this.$message.error('图片和视频，需要任意选择一个上传');
                            return;
                        }
                    }

                    //处理图片
                    if (this.surfacePlotList.length > 0) {
                        this.dataForm.surfacePlot = this.surfacePlotList.join(',');
                        params.surfacePlot = this.dataForm.surfacePlot;
                    }

                    //处理视频
                    if (this.videoUrlList.length > 0) {
                        this.dataForm.videoUrl = this.videoUrlList.join(',');
                        params.videoUrl = this.dataForm.videoUrl;
                    }

                    //  2.编辑
                    API.baseInfoManger.baseInfoListUpdate(params).then((data) => {
                        if (data.code == '0000') {
                            this.$message({
                                message: `${this.dialogType == 2 ? '修改成功' : '新增成功'}`,
                                type: 'success',
                                duration: 1500,
                                onClose: () => {
                                    if (this.dialogType == 2) {
                                        this.clearForm();
                                    }
                                    this.$router.go(-1);
                                }
                            });
                        } else {
                            this.$message.error(res.message);
                        }
                    });
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        }
    }
};
</script>

<style>
</style>